package com.lianboke.link.ad.activity;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.lianboke.link.ad.R;
import com.lianboke.link.ad.Views.CustomLoadingDialog;
import com.lianboke.link.ad.app.MyApplication;
import com.lianboke.link.ad.utils.DateUtil;
import com.lianboke.link.ad.utils.KLog;
import com.lianboke.link.ad.utils.SharedPreferencesUtil;
import com.umeng.analytics.MobclickAgent;


import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * 基础activity
 * Created by admin on 2017/9/6.
 */

public  abstract class BaseActivity extends AppCompatActivity {
    public Context appContext;
    public Context actContext;
    private Unbinder mUnbinder;
    private CustomLoadingDialog customLoadingDialog;
    private AlertDialog mUpdateAlertDialog;//升级对话框

    @BindView(R.id.iv_head_back)
    public ImageView iv_head_back;
    @BindView(R.id.tv_head_title)
    public TextView tv_head_title;

    @BindView(R.id.iv_head_more)
    public ImageView iv_head_more;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(getContentViewId());
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        mUnbinder = ButterKnife.bind(this);
        appContext = MyApplication.getAppContext();
        actContext = this;

        initActivityParams(savedInstanceState);

        //后退
        iv_head_back.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                TitleBackFinish();
            }
        });

        iv_head_more.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                TitleMoreActivity();
            }
        });
        if(initLocalBroadcastReceiver()){
            KLog.e("----------------BaseActivity---------initBroadcastReceiver-----------------");
            // 网络变更
            IntentFilter filter = new IntentFilter(
                    "com.sarnasea.interprocess.MYBROAD_ACTION");
            registerReceiver(networkreceiver, filter);

            //升级
            IntentFilter updatefilter = new IntentFilter();
            updatefilter.addAction("android.myapp.update.updatemy");
            registerReceiver(updateReceiver,updatefilter);

            //下载
            IntentFilter downloadfilter = new IntentFilter();
            downloadfilter.addAction("android.myapp.download.downloadmy");
            registerReceiver(downLoadReceiver,downloadfilter);

            //安装
            IntentFilter installfilter = new IntentFilter();
            installfilter.addAction("android.myapp.install.installmy");
            installfilter.addAction("android.myapp.install.removemy");
            installfilter.addAction("android.myapp.install.replacemy");
            registerReceiver(installReceiver,installfilter);

            //定时任务开始
            IntentFilter timerOrderfilter = new IntentFilter();
            timerOrderfilter.addAction("android.myapp.timer.orders.auto.start");
            timerOrderfilter.addAction("android.myapp.timer.orders.auto.stop");
            registerReceiver(timerOrderReceiver,timerOrderfilter);
        }
    }

    /**
     * title 的返回按钮
     */
    public void TitleBackFinish(){
        finish();
    }

    /**
     * title 的返回按钮
     */
    public void TitleMoreActivity(){

    }
    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        KLog.e("-------BaseActivity---------------onDestroy-----------");
        if(mUnbinder!=null){
            mUnbinder.unbind();
        }
        if(initLocalBroadcastReceiver()) {
            if (networkreceiver != null) {
                unregisterReceiver(networkreceiver);
            }
            if (updateReceiver != null) {
                unregisterReceiver(updateReceiver);
            }
            if (downLoadReceiver != null) {
                unregisterReceiver(downLoadReceiver);
            }
            if (installReceiver != null) {
                unregisterReceiver(installReceiver);
            }
            if(timerOrderReceiver!=null){
                unregisterReceiver(timerOrderReceiver);
            }
        }
        closedCustomerLoadingDialog();
    }

    /**
     * 加载activity 的布局u页面
     * @return
     */
    public abstract int getContentViewId();
    /**
     * 加载activity 的布局u页面
     * @return
     */
    public boolean initLocalBroadcastReceiver(){
        return  false;
    }
    /**
     * 处理activity 初始化操作
     * @param savedInstanceState
     */
    public abstract void initActivityParams(Bundle savedInstanceState);


    /**
     * 处理网络类型变更，本地广播
     * @param netType
     */
    public  void getMyBroadcastReceiver(String netType){

    }
    /**
     * 升级操作
     * @param action
     */
    public  void getUpdateMyBroadcastReceiver(String action){

    }

    /**
     * 下载操作
     * @param action
     */
    public  void getDownLoadMyBroadcastReceiver(String action){

    }
    /**
     * 安装操作
     * @param data
     */
    public  void getInstallMyBroadcastReceiver(String data){

    }
    /**
     * 定时任务操作
     * @param action
     */
    public  void getTimerOrderdMyBroadcastReceiver(String action){

    }
    /**
     * 卸载操作
     * @param data
     */
    public  void getRemoveMyBroadcastReceiver(String data){

    }
    /**
     * 替换操作
     * @param data
     */
    public  void getReplaceMyBroadcastReceiver(String data){

    }
    /**
     *  返回按钮是否显示
     * @param isShow
     */
    public void setTitleBackShow( boolean isShow){
        if(iv_head_back!=null){
            if(isShow){
                iv_head_back.setVisibility(View.VISIBLE);
            }else{
                iv_head_back.setVisibility(View.INVISIBLE);
            }
        }
    }
    /**
     *  返回按钮是否显示
     * @param isShow
     */
    public void setTitleMoreShow( boolean isShow){
        if(iv_head_more!=null){
            if(isShow){
                iv_head_more.setVisibility(View.VISIBLE);
            }else{
                iv_head_more.setVisibility(View.INVISIBLE);
            }
        }
    }
    /**
     * 设置title 内容
     * @param titleContent
     */
    public void setTitleContent(String titleContent){
        if(tv_head_title!=null){
            tv_head_title.setText(titleContent);
        }
    }


    //====================================

    /**广播接收器*/
    private BroadcastReceiver networkreceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            //接收到广播后进行的操作
            String data = intent.getStringExtra("data");
            getMyBroadcastReceiver(data);
        }
    };

    //升级接收器
    private BroadcastReceiver updateReceiver = new BroadcastReceiver() {

                @Override
                public void onReceive(Context context, Intent intent) {
                    //接收到广播后进行的操作
                    String data = intent.getStringExtra("data");
                    getUpdateMyBroadcastReceiver(data);
                }
            };

    //下载接收器
    private BroadcastReceiver downLoadReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            //接收到广播后进行的操作
            String data = intent.getStringExtra("data");
            KLog.e("----------------BaseActivity----downLoadReceiver---------:"+data);
            getDownLoadMyBroadcastReceiver(data);
        }
    };

    //安装接收器
    public BroadcastReceiver installReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            //接收到广播后进行的操作
            String strAction = intent.getAction();
            KLog.e("----------------BaseActivity----installReceiver-----:"+strAction);
            if("android.myapp.install.installmy".equals(strAction)){
                //安装
                String data = intent.getStringExtra("data");
                getInstallMyBroadcastReceiver(data);
            }else if("android.myapp.install.removemy".equals(strAction)){
                //卸载
                String data = intent.getStringExtra("data");
                getRemoveMyBroadcastReceiver(data);
            }else if("android.myapp.install.replacemy".equals(strAction)){
                //替换
                String data = intent.getStringExtra("data");
                getReplaceMyBroadcastReceiver(data);
            }
        }
    };

    //任务定时器
    private BroadcastReceiver timerOrderReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            //接收到广播后进行的操作
            String data = intent.getStringExtra("data");
            KLog.e("----------------BaseActivity----timerorder---------:"+data);
            String strAction = intent.getAction();
            int iCacheHours =  ((Integer) SharedPreferencesUtil.getData(actContext,"time_order_hourOfday",-1)).intValue();
            int iCacheMinute =  ((Integer)SharedPreferencesUtil.getData(actContext,"time_order_minute",-1)).intValue();
            int iHH = Integer.valueOf(DateUtil.getCurDateStr("HH"));
            int iMM = Integer.valueOf(DateUtil.getCurDateStr("mm"));
            KLog.e("check_timer_log","--------iCacheHours--------:"+iCacheHours);
            KLog.e("check_timer_log","--------iCacheMinute--------:"+iCacheMinute);
            KLog.e("check_timer_log","--------iHH--------:"+iHH);
            KLog.e("check_timer_log","--------iMM--------:"+iMM);

            if("android.myapp.timer.orders.auto.start".equals(strAction)) {
                //启动定时
                if (iCacheHours >= iHH && iCacheMinute >= iMM) {
                    //小时相等,定时分钟大于等于当前分钟
                    KLog.e("check_timer_log", "--------1--------");
                    getTimerOrderdMyBroadcastReceiver(data);
                } else {
                    //定时过期
                }
            }else if("android.myapp.timer.orders.auto.stop".equals(strAction)){
                //结束定时
                getTimerOrderdMyBroadcastReceiver(data);
            }
        }
    };


//=========================dialog=============================


    /**
     * 展示对话框
     * @param content
     */
    public void showAlerDialog(String content){
        new AlertDialog.Builder(this)
                .setTitle("提示")
                .setMessage(content)
                .setCancelable(false)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .create().show();
    }

    /**
     * 关闭对话框
     * @param content
     */
    public void showFinishDialog(String content){
        new AlertDialog.Builder(this)
                .setTitle("提示")
                .setMessage(content)
                .setCancelable(false)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        finish();
                    }
                })
                .create().show();

    }
    /**
     *初始化升级对话框
     * @param content
     */
    public void initUpdateDialog(String content){
       mUpdateAlertDialog =  new AlertDialog.Builder(this)
                .setTitle("提示")
                .setMessage(content)
                .setCancelable(false)
                .create();
       mUpdateAlertDialog.show();
      }

    /**
     * 显示升级
     */
    public void showUpdateAlearDialog(String content){
        if(mUpdateAlertDialog==null){
            initUpdateDialog(content);
        }else if(!mUpdateAlertDialog.isShowing()){
            mUpdateAlertDialog.show();
        }
        if(!TextUtils.isEmpty(content)){
            mUpdateAlertDialog.setMessage(content);
        }

      }
    /**
     * 隐藏升级
     */
    public void dismissUpdateAlearDialog(){
        if(mUpdateAlertDialog!=null && mUpdateAlertDialog.isShowing()){
            mUpdateAlertDialog.dismiss();
        }
    }

    /**
     * 初始化自定义加载对话框
     */
    public void initCustomerLoadingDialog(String strContent){
        if(customLoadingDialog==null){
            customLoadingDialog = new CustomLoadingDialog(actContext,strContent,false);
        }else{
            customLoadingDialog.updateLoadDialogContent(strContent);
        }
        customLoadingDialog.show();
    }
    /**
     * 关闭自定义对话框
     */
    public void closedCustomerLoadingDialog(){
        if(customLoadingDialog!=null){
            customLoadingDialog.dismiss();
        }
        customLoadingDialog = null;
    }

    /**
     * 设置
     * @param value
     */
    public void setCustomLoadingDialogProgressValue(int value){
        if(customLoadingDialog!=null){
            customLoadingDialog.setProgressBarKey(value);
            customLoadingDialog.setProgressBarValue(value);
        }
    }

    /**
     * 设置是否显示或隐藏进度条
     * @param isShow
     */
    public void setShowAndHideCustomLoadingProgress(boolean isShow){
        if(customLoadingDialog!=null){
            customLoadingDialog.setShowAndHideProgressBarUI(isShow);
        }
    }



    /**
     * 更新自定义对话框内容
     * @param strContent
     */
    public void updateCustomerLoadingDialog(String strContent){
        if(customLoadingDialog!=null && customLoadingDialog.isShowing()){
            customLoadingDialog.updateLoadDialogContent(strContent);
        }
    }
}
